import { StorageService } from './../../providers/StorageService';
import { StyleService } from './../../providers/StyleService';
import { BasePage } from './../basePage';
import { Component, Injector, ViewChild } from '@angular/core';
import { IonicPage, Slides } from 'ionic-angular';
import { PIC_URL } from './../../providers/Config';
import { HTTP } from '@ionic-native/http';
declare var layer;

declare var $: any;
declare var cordova: any;
/**
 * Generated class for the ImgInfoPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
	selector: 'page-img-info',
	templateUrl: 'img-info.html',
	providers: [StyleService, StorageService]
})
export class ImgInfoPage extends BasePage {
	err: string;
	success: string;
	html: any;
	nailName: any;
	outTradeNo: any;
	showZank: boolean;
	@ViewChild(Slides) slides: Slides;

	shopInfoData: boolean;
	version: any;
	userinfo: any;
	picture: string;

	nail_info = [];
	shop_info = [];
	NailDetailsData = {
		nail_info: [],
		shop_info: [],
		comments: [],
		is_collected: '',
		is_focus: '',
		is_zank: '',
		artist_id: '',
		zank_count: '',
		collect_count: ''
	};
	comments = [];
	ids: any;
	data = {
		user_id: '',
		nail_id: ''
	};
	data1 = {
		user_id: '',
		nail_id: '',
		comment_content: ''
	};
	data2 = {
		focused_id: '',
		user_id: ''
	};
	data3 = {
		user_id: '',
		collected_id: '',
		collect_type: 1
	};
	data4 = {
		user_id: '',
		nail_id: ''
	};
	oboaut = '';
	oboaut1 = '';
	oboaut2 = '';
	msg: '';
	artist_level;
	img: boolean = false
	show: boolean = false;
	selects = [
		{ day: '1', price: '1' },
		{ day: '7', price: '7' },
		{ day: '15', price: '15' },
		{ day: '30', price: '30' },
	]
	selectItem = {
		day: '',
		price: ''
	};



	/**店主购买美甲款式 */
	BuyNail = {
		nail_id: null,
		shop_id: null,
		order_price: null,
		buy_days: null
	};

	constructor(injector: Injector, private http: HTTP, public styleProvider: StyleService, public stc: StorageService) {
		super(injector);
		this.picture = PIC_URL;
		this.userinfo = this.stc.read('userinfo');

		/*判断用户是否登录*/
		if (this.userinfo === null) {
			this.data.user_id = '';
			this.BuyNail.shop_id = '';
			this.showZank = false;
		} else {
			this.data.user_id = this.userinfo.user_id;
			this.BuyNail.shop_id = this.userinfo.shop_id;
			console.log(this.userinfo);
			let userType = this.userinfo.user_type.split(',');
			// console.log(userType);
			// console.log(userType.indexOf("3"))
			if (userType.indexOf('3') > -1) {
				console.log('我是店主');
				this.showZank = true;
			} else {
				this.showZank = false;
			}
		}
	}


	ionViewDidLoad() {
		/*获取当前美甲款式的 nail_id */
		this.ids = this.navParams.get('id');
		this.artist_level = this.navParams.get('artist_level')
		console.log(this.artist_level)
		this.BuyNail.nail_id = this.data.nail_id = this.ids;

		console.log(this.data);
		console.log('ionViewDidLoad ImgInfoPage');
		this.getNailDetailsAPI();
	}
	// 模态框确认购买天数
	async submit() {
		this.BuyNail.order_price = this.selectItem.price;
		this.BuyNail.buy_days = this.selectItem.day;
		this.show = false;
		console.log(this.BuyNail)
		let res = await this.styleProvider.shopkeeperBuyNailAPI(this.BuyNail);
		if (res.code == 0) {
			this.showAlert('请选择商品')
		} else if (res.code == 1) {
			this.outTradeNo = res.data.order_sn;
			console.log(this.outTradeNo)
			this.gotopay();
		}

		console.log(res);
	}
	/** 返回 */
	diss() {
		console.log(111);
		let data = { foo: 'bar' };
		this.viewCtrl.dismiss(data);
	}


	/** 跳转 */
	shopInfo(i) {
		console.log(i);

		this.navCtrl.push('ShopInfoPage', {
			id: this.NailDetailsData.shop_info[i].service_id,
			shop_id: this.NailDetailsData.shop_info[i].shop_id
		});
		console.log(this.NailDetailsData.shop_info[i].service_id);
	}

	/** 关注 */
	obout(stu) {
		this.focusAPI();
		if (this.userinfo != null) {
			this.oboaut = stu;
		}
		console.log(this.oboaut);
	}
	/** 点赞 */
	obout1(stu) {
		if (this.userinfo == null) {
			this.zankNailAPI();
			return;
		} else {
			this.zankNailAPI();
		}

		this.oboaut1 = stu;
	}

	// showRadio() {
	// 	let alert = this.alertCtrl.create();
	// 	alert.setTitle('Lightsaber color');

	// 	alert.addInput({
	// 		type: 'radio',
	// 		label: '1天        ￥ 1.00',
	// 		value: '1',
	// 		checked: false
	// 	});
	// 	alert.addInput({
	// 		type: 'radio',
	// 		label: '7天         ￥7.00',
	// 		value: '7',
	// 		checked: false
	// 	});
	// 	alert.addInput({
	// 		type: 'radio',
	// 		label: '15天         ￥15.00',
	// 		value: '15',
	// 		checked: false
	// 	});

	// 	alert.addButton('取消');
	// 	alert.addButton({
	// 		text: '确认支付',
	// 		handler: (data) => {
	// 			console.log(data);
	// 			this.BuyNail.buy_days = data;
	// 			if (data == 1) {
	// 				this.BuyNail.order_price = 1.0;
	// 			} else if (data == 7) {
	// 				this.BuyNail.order_price = 7.0;
	// 			} else if (data == 15) {
	// 				this.BuyNail.order_price = 15.0;
	// 			}
	// 			// console.log(this.BuyNail);
	// 			// let res = this.styleProvider.shopkeeperBuyNailAPI(this.BuyNail);
	// 			// console.log(res);

	// 			this.shopkeeperBuyNailAPI();
	// 			// this.testRadioOpen = false;
	// 			// this.testRadioResult = data;
	// 		}
	// 	});
	// 	alert.present();
	// }
	/**跳转美甲师详情 */
	GoMages(stu) {
		console.log(this.data.user_id)
		console.log(stu)
		if (this.data.user_id == null) {
			let toast = this.toastCtrl.create({
				message: '您还没登录呢！',
				duration: 2000,
				position: 'top'
			});
			toast.onDidDismiss(() => {
				console.log('Dismissed toast');
			});

			toast.present();
		} else {
			let nailerdetail = {
				user_id: this.userinfo.user_id,
				artist_id: this.NailDetailsData['artist_id']
			}
			this.navCtrl.push('NailerDetailPage', {
				nailerdetail
			})
		}

		// console.log(nailerdetail)

	}
	/**店主购买美甲款式 */
	async shopkeeperBuyNailAPI() {
		console.log(this.BuyNail);
		let res = await this.styleProvider.shopkeeperBuyNailAPI(this.BuyNail);
		console.log(res);
		if (res.code == 1) {
			console.log(res.data.order_sn);
			this.outTradeNo = res.data.order_sn;
			this.gotopay();
		} else if (res.code == 0) {
			this.toastCtrl
				.create({
					message: res.msg,
					duration: 3000,
					position: 'middle'
				})
				.present();
		}
	}

	/**去支付 */
	gotopay() {
		this.actionCtrl
			.create({
				buttons: [
					{
						text: '支付宝支付',
						handler: () => {
							//let alipaystr = this.editOrderAPI(item);

							this.aliPay();
						}
					},
					// {
					// 	text: '微信支付',
					// 	handler: () => {
					// 		this.aliPay2();
					// 	}
					// },
					{
						text: '取消',
						role: 'cancel'
					}
				]
			})
			.present();
	}
	unescapeHTML(a) {
		//let aNew = "" + a;
		let str =
			'app_id=2016121504287738&biz_content=%7B%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%22laravel%22%2C%22out_trade_no%22%3A%22SN23788%22%2C%22total_amount%22%3A120%2C%22body%22%3A%22%22%22seller_id%22%3A%2218827403620%40139.com%22%7D&charset=UTF-8&format=JSON&method=alipay.trade.app.pay&notify_url=http%3A%2F%2F192.168.1.99%3A1114%2FAdmin%2FAlipay%2Fnotifyurl&sign_type=RSA&timestamp=2018-02-09+09%3A52%3A06&version=1.0&sign=jVC%2FjWMqeVaKTOM4mntqV6hiSUC1Kn5SVHG981up1taiUGCHIQpHAz%2BqEz9%2FSjNRLhoMNEaYJGRf4E5fmkjzM6MBPQkGywFabZ%2Fr%2Bk0t6Iyrq9AKu6i1O0STSzTjjAaS9y%2BaQpq5fSJ190FLVfKAzstYuhVUXkCNw%2B%2FWCff4dt8%3D';
		//return aNew.replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&").replace(/"/g, '"').replace(/'/g, "'");
		return str;
	}
	// aliPay() {
	// 	console.log(333);
	// 	console.log(this.nailName);
	// 	console.log(this.outTradeNo);
	// 	console.log(this.BuyNail.order_price)
	// 	$.post(
	// 		'http://116.62.162.165:1228/api/alipay/uniformPayGateway',
	// 		{
	// 			subject: this.nailName,
	// 			outTradeNo: this.outTradeNo,
	// 			totalAmount: 0.01,
	// 			// totalAmount: this.BuyNail.order_price,
	// 			payType: 2
	// 		},
	// 		(data) => {
	// 			//let payInfo=this.unescapeHTML(data);
	// 			console.log(data);

	// 			cordova.plugins.alipay.payment(
	// 				data,
	// 				(success) => { },
	// 				(error) => {
	// 					return;
	// 				}
	// 			);
	// 		}
	// 	);
	// }






  async	getData() {
		let url: string = 'http://116.62.162.165:1228/api/alipay/uniformPayGateway'; //服务器端接口
		let bodyParams = {
			subject: this.nailName,
			outTradeNo: this.outTradeNo,
			totalAmount: 0.01,
			// totalAmount: this.BuyNail.order_price,
			payType: 2
		}
		this.http.post(url, bodyParams, {}).then(obj => {

			this.html = obj;
			console.log("我是post里面的参数")
			console.log(obj);

		}).catch(err => {
			console.log(err.status);
		});

	}

	goToPay() {

		cordova.plugins.alipay.payment(this.html, (success) => {

			// alert(success);

			this.success = JSON.stringify(success); //处理成功的信息
			console.log(this.success)
		}, (error) => {

			// console.log(error);

			this.err = JSON.stringify(error);

			console.log(JSON.stringify(error));

		});

	}



	aliPay() {


		// this.getData();
		// this.goToPay();


		console.log(333);
		console.log(this.nailName);
		console.log(this.outTradeNo);
		console.log(this.BuyNail.order_price)
		$.post(
			'http://116.62.162.165:1228/api/alipay/uniformPayGateway',
			// 'http://192.168.1.99:7777/admin/api/pay',
			{
				subject: this.nailName,
				outTradeNo: this.outTradeNo,
				totalAmount: 0.01,
				// totalAmount: this.BuyNail.order_price,
				payType: 2
			},
			(data) => {
				//let payInfo=this.unescapeHTML(data);
				console.log(data);

				cordova.plugins.alipay.payment(
					data,
					(success) => { },
					(error) => {
						return;
					}
				);
			}
		).then((data) => {
			(data) => {
				//let payInfo=this.unescapeHTML(data);
				console.log(data);
				console.log("我是then里面的方法")
				cordova.plugins.alipay.payment(
					data,
					(success) => { },
					(error) => {
						return;
					}
				);
			}
		})
	}

	aliPay2() {
		$.post(
			'http://192.168.1.99:1114/api/common/uniformPayer',
			{
				pay_type: 1,
				out_trade_no: 'SN23788',
				subject: 'laravel',
				total_amount: 0.01,
				alipay_type: 2
			},
			(data) => {
				//let payInfo=this.unescapeHTML(data);
				console.log(data);
				data = this.unescapeHTML(data);

				console.log(data);

				cordova.plugins.alipay.payment(data, (success) => { }, (error) => { });
			}
		);
	}

	/** 收藏 */
	obout2(stu) {
		this.collectionAPI();
		if (this.userinfo != null) this.oboaut2 = stu;

	}
	/** 获取详情信息 */
	async getNailDetailsAPI() {
		//this.data.user_id = this.userinfo.user_id;
		let res = await this.styleProvider.getNailDetailsAPI(this.data);
		console.log(res);
		this.NailDetailsData = res.data;
		this.nailName = res.data.nail_info.nail_name;
		this.nail_info = this.NailDetailsData.nail_info;
		if (this.NailDetailsData.shop_info.length != 0) {
			this.shop_info = this.NailDetailsData.shop_info;
			this.shopInfoData = true;
		} else {
			this.shopInfoData = false;
		}
		// console.log(this.NailDetailsData);

		this.comments = this.NailDetailsData.comments.reverse();
		// this.NailDetailsData.collect_count=res.

		console.log(res);
		console.log(this.NailDetailsData);
		console.log(this.comments);
		this.oboaut2 = this.NailDetailsData.is_collected;
		this.oboaut = this.NailDetailsData.is_focus;

		/*用来表示 当前用户是否已经点赞*/
		this.oboaut1 = this.NailDetailsData.is_zank;
		// console.log(this.oboaut);
		console.log(this.oboaut2);
	}
	/**合作美店 滑动 */
	slideChanged() {
		// let currentIndex = this.slides.length();
		// console.log('Current index is', currentIndex);
		// let currentPage=Math.ceil(currentIndex/4)
		// console.log(this.slides.isEnd())
		// if (this.slides.isEnd()) {
		//   this.slides.lockSwipeToPrev(true);
		// }
		this.slides.lockSwipeToPrev(true);
		this.slides.lockSwipeToNext(true);
	}
	/** 评论 */
	InputCLI(type, inputname, placeholder, fontnum) {
		if (this.userinfo == null) {
			let alert = this.alertCtrl.create({
				title: '登录提示',
				subTitle: '未登录，请先登陆',
				buttons: [
					{
						text: '取消',
						handler: (data) => { }
					},
					{
						text: '去登录',
						handler: (data) => {
							let modal = this.modalCtrl.create('LoginPage');
							modal.onDidDismiss((data) => { });
							modal.present();
						}
					}
				]
			});
			alert.present();
		} else {
			let inputvalue = '评论';
			this.openTextArea('评论', '', (data) => {
				console.log(data);
				this.data1.comment_content = data;
				console.log(this.data1.comment_content);
				if (typeof this.data1.comment_content == 'string') {
					this.publishCommentAPI();
				}
			});
		}
	}
	/** 跳转购买 */
	changeVersion(stu) {
		if (this.userinfo == null) {
			let alert = this.alertCtrl.create({
				title: '登录提示',
				subTitle: '未登录，请先登陆',
				buttons: [
					{
						text: '取消',
						handler: (data) => { }
					},
					{
						text: '去登录',
						handler: (data) => {
							let modal = this.modalCtrl.create('LoginPage');
							modal.onDidDismiss((data) => { });
							modal.present();
						}
					}
				]
			});
			alert.present();
		} else if (this.userinfo['user_type'] == '1,2,3' || this.userinfo['user_type'] == '1,2') {
			if (this.NailDetailsData.is_zank == '1') {
				this.oboaut1 = '1';
				console.log(1);
				this.zankNailAPI();
				return;
			} else {
				this.oboaut1 = stu;
				console.log(2);
				console.log(this.oboaut1);
				this.zankNailAPI();
			}
			// if (this.version != '') {
			//   this.navCtrl.push("OrderConfirmationPage", { "day": this.version });
			//   this.version = '';
			// }
		} else {
			// this.showAlert("您当前身份不是美甲师，不能点赞哦！")
		}
	}
	/** 评论 */
	async publishCommentAPI() {
		this.data1.user_id = this.userinfo.user_id;
		this.data1.nail_id = this.ids;
		console.log(this.data1);
		let res = await this.styleProvider.publishCommentAPI(this.data1);
		if (res.code == 1) {
			this.msg = res.msg;
			this.presentToast();
			this.getNailDetailsAPI();
		} else {
			this.msg = res.msg;
			this.presentToast();
		}
	}
	/** 关注 */
	async focusAPI() {
		if (this.userinfo == null) {
			this.showAlert('您当前未登录，请登录后操作！');
		} else {
			this.data2.user_id = this.userinfo.user_id;
			this.data2.focused_id = this.NailDetailsData.artist_id;
			console.log(this.data2);
			let res = await this.styleProvider.focusAPI(this.data2);
			if (res.code == 1) {
				this.msg = res.msg;
				this.presentToast();
				this.getNailDetailsAPI();
			} else {
				this.msg = res.msg;
				this.presentToast();
			}
		}
	}

	/** 收藏 */
	async collectionAPI() {
		if (this.userinfo == null) {
			this.showAlert('您当前未登录，请登录后操作！');
		} else {
			this.data3.user_id = this.userinfo.user_id;
			this.data3.collected_id = this.ids;
			console.log(this.data3);
			let res = await this.styleProvider.collectionAPI(this.data3);
			console.log(res)
			if (res.error_code == 0) {
				this.msg = res.msg;
				// console.log(res.data.collect_count);
				this.presentToast();
				this.getNailDetailsAPI();
			} else {
				this.msg = res.msg;
				this.presentToast();
			}
		}
	}
	/** 点赞 */
	async zankNailAPI() {
		if (this.userinfo == null) {
			this.showAlert('您还未登陆，请登陆后操作！');
		} else {
			this.data4.user_id = this.userinfo.user_id;
			this.data4.nail_id = this.ids;

			let res = await this.styleProvider.zankNailAPI(this.data4);

			if (res.error_code == 0) {
				this.msg = res.msg;
				this.presentToast();
				this.getNailDetailsAPI();
			} else {
				this.msg = res.msg;
				this.presentToast();
				return;
			}
		}
	}
	/** 提示 */
	presentToast() {
		let toast = this.toastCtrl.create({
			message: this.msg,
			duration: 2000,
			position: 'top'
		});
		toast.onDidDismiss(() => {
			console.log('Dismissed toast');
		});

		toast.present();
	}
	browseAll() {
		this.navCtrl.push('BrowseShopPage', { nail_id: this.ids });
	}
}
